<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\book\controller\member;

use app\book\base\BookMemberBase;

use think\Session;
use think\Cache;
use app\member\model\Member as MemberModel;

class Login extends BookMemberBase{
    // 第三方登录配置信息
    private $config;
    // 第三方登录类型
    private $oauth;
    // 第三方登录类
    private $classObj;
	/**
     * 会员登录
     * @access public
     * @return \think\Response
     */
    public function index(){
        if(!Session::has('backurl')){
            $backurl = '';
            if(in_array($this->currentActionUrl, $this->logged_deny)){
                $backurl = 'book/member.Index/index';
            }else{
                $backurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'book/member.Index/index';
            }
            Session::set('backurl', $backurl);
        }
        if($this->request->isPost()){
            $post_data = $this->buildParam();
            $member = new MemberModel;
            $uid = $member->login($post_data['username'], $post_data['password']);
            if($uid>0){
                // 保存会员uid到session
                Session::set('member_uid', $uid);
                // 执行跳转
                $redirect_url = Session::get('backurl');
                Session::delete('backurl');
                $this->redirect($redirect_url);
            }else{
                $this->error($member->getError());
            }
        }
        return $this->getTemplate();
    }

    /**
     * ajax会员登录
     * @access public
     * @return mixed
     */
    public function ajaxLogin(){
        $status = 0;
        $msg = '';
        $post_data = $this->buildParam();
        $member = new MemberModel;
        $uid = $member->login($post_data['username'], $post_data['password']);
        if($uid>0){
            $status = 1;
            $msg = '欢迎回来';
            // 保存会员uid到session
            Session::set('member_uid', $uid);
        }else{
            $msg = $member->getError();
        }
        return json(['status' => $status, 'msg' => $msg]);
    }

    /**
     * 第三方登录
     * @access public
     * @return mixed
     */
    public function thirdLogin(){
        if(!Session::has('backurl')){
            Session::set('backurl', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'book/member.Index/index');
        }
        $this->oauth = $this->request->param('oauth');
        if(!$this->oauth){
            $this->error('非法操作');
        }
        include_once  '../manniu/plugins/login/'.$this->oauth.'/'.$this->oauth.'.class.php';
        $class = '\\'.$this->oauth;
        $this->classObj = new $class; // 实例化对应的登陆插件
        $this->classObj->login();
    }

    /**
     * 第三方登录回调
     * @access public
     * @return mixed
     */
    public function callback(){
        $this->oauth = $this->request->param('oauth');
        if(!$this->oauth){
            $this->error('非法操作');
        }
        include_once  '../manniu/plugins/login/'.$this->oauth.'/'.$this->oauth.'.class.php';
        $class = '\\'.$this->oauth;
        $this->classObj = new $class; // 实例化对应的登陆插件
        $data = $this->classObj->respon();
        if($this->uid){
            $this->error('当前已存在登录帐号，请勿重复登录！');
        }

        $openid = $data['openid']; //第三方返回唯一标识
        $oauth = $data['oauth']; //来源
        if(!$openid || !$oauth){
            $this->error('参数有误');
        }
        //获取用户信息
        if(isset($data['unionid'])){
            $map['unionid'] = $data['unionid'];
            $member = MemberModel::get(['unionid'=>$data['unionid'],'oauth'=>$oauth]);
        }else{
            $member = MemberModel::get(['openid'=>$openid,'oauth'=>$oauth]);
        }
        if(!$member){
            // 账户不存在 注册一个
            $salt = substr(md5(rand(0, 999)), 0, 10);
            $password = substr(md5(rand(0, 999)), 0, 10);
            $nickname = $data['nickname'];
            if(!empty($nickname)){
                $result = MemberModel::get(['nickname' => $nickname]);
                if($result){
                    $nickname = $nickname.rand(100,999);
                }
            }
            $nickname = $nickname ? $nickname : null;
            $member = MemberModel::create([
                'username'          => 'mnrm'.date("YmdHi").rand(1000000,9999999),
                'password'          => $password,
                'salt'              => $salt,
                'nickname'          => $nickname,
                'mobile'            => null,
                'email'             => null,
                'avatar'            => !empty($data['avatar']) ? $data['avatar'] : null,
                'chargeable'        => 0,
                'read_money'        => 0,
                'group_id'          => 1,
                'regip'             => $this->request->ip(),
                'oauth'             => $oauth,
                'openid'            => $openid,
                'unionid'           => isset($data['unionid']) ? $data['unionid'] : null,
                'last_login_time'   => time()
            ]);
        }else{
            // 更新会员登录信息
            $member->last_login_time    = time();
            $member->last_login_ip      = $this->request->ip();
            $member->save();
        }
        // 保存会员uid到session
        Session::set('member_uid', $member->uid);
        // 执行跳转
        $redirect_url = Session::get('backurl');
        Session::delete('backurl');
        $this->redirect($redirect_url);
    }

    /**
     * 退出登录
     * @access public
     * @return void
     */
    public function logout(){
        Session::clear();
        $this->redirect('/');
    }
}